package com.example.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@RestController
@RequestMapping("/upload")
//@CrossOrigin
public class UploadController {
    @PostMapping("/img")
    public String upload(MultipartFile file){

//        1.需要定义该图片存放的位置
//        String folder="D:\\springbootworkspace\\demo2\\my-project-two\\static\\image";

        String folder="D:\\cwc\\VUE\\my-project-first\\static\\image";
        //2.文件夹
        File imgFolder=new File(folder);
        //3.获取上传文件的名称
        String filename=file.getOriginalFilename();
        //4.获取文件后缀
        String ext =filename.substring(filename.lastIndexOf("."));
        //5.获取上传时间
        String format= DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
        //6.uutd随机数
        String uuid  = UUID.randomUUID().toString().replaceAll("-","");
        //7.全新的文件名
        String  fileNewName=format+uuid+ext;
        //8.文件上传
        File file1= new File(imgFolder,fileNewName);
        if (!file1.getParentFile().exists()){
            /**
             * 为了防止上传文件时 文件不存在，所以进行判断
             * 不存在的话进行创建
             */
            file1.getParentFile().mkdirs();
        }
        try {
            file.transferTo(file1);
            //返回文件名
            return file1.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
